<template>
    <div>
        <Row>
            <!-- 查询区域 -->
            <div style="margin-left:10px">
                <div style="width:250px;">
                    <Form ref="select"  label-position="left"  :label-width="80">
                        <Form-Item  prop="region_id" label="选择区域:" >
                            <Select v-model="region_id"  @on-change="changeRegion">
                                <Option v-for="region in region_list" :key="region.RegionId" :value="region.RegionId">{{ region.LocalName }}</Option>
                            </Select>
                        </Form-Item>
                    </Form> 
                </div>
                <!-- <div>
                    <Button  size="default"  type="error" style="margin-bottom: 5px ;margin-right:5px;margin-left: 5px;"  @click="btn_select_instance">查询</Button>
                </div> -->
            </div>
        </Row>
        <i-table size="default"   border stripe  :columns="format" :data="show_list" :height="sharedState.tableHeight" >
            <template slot-scope="{ row, index }" slot="action">
                <Button  size="default"  type="primary"   style="margin-bottom: 5px "  @click="btn_ssh_connect(index)">ssh</Button>
            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" @on-page-size-change="changePageSize" show-total show-sizer/>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import { post } from  '@/api/http'
import store from '@/store'
import { get_server_list,get_region_list,get_cloud_key_pair } from  '@/api'
import { get_placement,utcToBeijing } from '@/common/util.js'

export default {
    data() {
        return {
            sharedState: store.state,
            format: [
                {
                    title: '实例Id',key: 'InstanceId'
                },
                {
                    title: '标签',key: 'Tags',
                    render: (h, params) => {
                        let tags = params.row.Tags
                        if(tags == null){
                            return h('p','无')
                        }else {
                            let value = JSON.stringify(tags,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);


                        }
                    }
                },
                // {
                //     title: '监控',key: 'InstanceId'
                // },
                {
                    title: '可用区',key: 'ZoneId'
                },
                {
                    title: 'IP地址',width:250,
                    render: (h, params) => {
                        let PublicIp = params.row.PublicIpAddress.IpAddress
                        let PrivateIp = params.row.VpcAttributes.PrivateIpAddress.IpAddress
                        let value = PublicIp+" (公有)"+"\n"+PrivateIp+" (私有)"
                        return h('pre',value)

                    }
                },
                {
                    title: '状态',key: 'Status',
                    align: 'center',
                    render:(h,params) => {
                        if(params.row.Status=='Running'){
                            return h('span',{
                                style: {
                                    color: '#19be6b',
                                }
                            },params.row.Status)
                        }else if (params.row.Status=='Pending'){
                            return h('span',{
                                style: {
                                    color: '#ff9900'
                                }
                            },params.row.Status)
                        }else if (params.row.Status=='Stopped'){
                            return h('span',{
                                style: {
                                    color: '#ed4014'
                                }
                            },params.row.Status)
                        }else {
                            return h('span',{},params.row.Status)
                        }
                    }
                },
                {
                    title: '网络类型',key: 'InstanceNetworkType'
                },
                {
                    title: '配置',width:300,
                    render: (h, params) => {
                        let cpu = params.row.Cpu
                        let memory = params.row.Memory
                        let io = params.row.IoOptimized
                        let instanceType = params.row.InstanceType
                        let bandwidth=  params.row.InternetMaxBandwidthOut
                        let value = undefined
                        if (io){
                            value = cpu+" vCPU"+memory+" MB"+" （I/O优化）"+"\n"+instanceType+" "+bandwidth+"Mbps （峰值）"
                        }else {
                            value = cpu+" vCPU"+memory+" MB"+"\n"+instanceType+" "+bandwidth+"Mbps （峰值）"
                        }
                        return h('pre',value)

                    }
                    // 1 vCPU 512 MB （I/O优化）
                    // ecs.t5-lc2m1.nano   2Mbps （峰值）
                },
                {
                    title: '付费方式',key: 'InstanceChargeType'
                    // 按量-抢占式实例
                    
                },
                {
                    title: '创建时间',key: 'CreationTime',
                    render:(h,params) =>{
                        let t = params.row.CreationTime
                        let value = utcToBeijing(t)
                        return h('span',value)
                    }
                    // 2021年1月23日 22:18 创建
                },
                {
                    title: '自动释放时间',key: 'AutoReleaseTime',
                    render:(h,params) =>{
                        let t = params.row.AutoReleaseTime
                        let value = utcToBeijing(t)
                        return h('span',value)
                    }
                    // 2021年1月23日 22:18 创建
                },

                {
                    title: '操作',slot: 'action',width: 100,align: 'center'
                }
            ],
            // 分页
            show_list: [],
            total: 0,
            pageSize: 10,
            page: 1,
            // 区域列表
            region_list:[],
            region_id:'cn-shenzhen',
            ssh_key:'',
        }
    },
    methods: {
        changePage(page) {
            this.page=page
            this.refresh()
        },
        // 每页条数变更
        changePageSize(pageSize){
            console.log(pageSize)
            this.pageSize = pageSize
            this.refresh()
        },
        // 获取区域列表
        regionList(){
            post(get_region_list).then(response =>{
                // console.log(response.data)
                let data = response.data
                this.region_list = data.Regions.Region
                console.log(this.region_list.length)
            })
        },

        changeRegion() {
            let region_id = this.region_id
            localStorage.setItem("aliyun_region_id",region_id)
            this.refresh()
        },
        async get_ssh_key(){
            try {
                let response = await axios({url: get_cloud_key_pair,method: 'post'})
                let data = response.data
                console.log(data)
                this.ssh_key =data.content

                console.log("ssh_key:",this.ssh_key)
            } catch (error) {
                console.log(error)
                return null;
            }
        },
        // 连接ssh
        async btn_ssh_connect(index){
            let status = this.show_list[index].Status
            // if(status != 'Running' && status != 'Pending'){
            if(status != 'Running'){
                this.$Message.error('非在线主机不能连接')
                return
            }
            let ip = this.show_list[index].PublicIpAddress.IpAddress
            console.log(index,ip)
            // 获取系统ssh账号
            await this.get_ssh_key()
            let  webssh_url = process.env.VUE_APP_WEBSSH_URL
            let ssh_key = window.btoa(this.ssh_key)
            console.log(ssh_key)
            // let ssh_key = this.ssh_key

            // let url = 'http://192.168.11.201:8888?hostname='+ip+'&port='+'22'+'&username='+'root'+'&password='+'RnIxNjgyOTk4NyNAIQo='
            // "privatekey"
            //  let url = 'http://192.168.11.201:8888?hostname='+ip+'&port='+'22'+'&username='+'root'+'&password='+'121'
            let url = webssh_url+'?hostname='+ip+'&port='+'22'+'&username='+'root'+'&passphrase='+'123456'+'&privatekey='+ssh_key
            // console.log(url)
            window.open(url,"_blank");

        },
        region_list_have_id(id){
            console.log("id="+id+this.region_list.length)
            let region_list = this.region_list
            let exist = false
            for(let i=0;i< region_list.length;i++){
                let region_id = region_list[i].RegionId
                // console.log(region_list[i].RegionId)
                if(region_id==id){
                    exist = true
                    break
                }
            }
            return exist
        },
        refresh() {
            if(this.region_list.length == 0){
                this.$Message.error("获取区域列表失败")
                return
            }
            let region_id = localStorage.getItem("aliyun_region_id")
            
            // bug 切换集群，节点选中丢失，已判断
            console.log(!this.region_list_have_id(region_id))
            // 缓存没有 或者列表中不含此项
            if(! region_id || !this.region_list_have_id(region_id) ){
                // this.region_id = 'cn-hangzhou'
                this.region_id = this.region_list[0].RegionId
            }else{
                // 重设选中项
                this.region_id = region_id
            }
            let params = {
                "pageSize":this.pageSize,
                "page":this.page,
                "region_id":this.region_id
            }
            post(get_server_list,{},{},3000,params).then(response=>{
                // console.log(response.data)
                let data = response.data
                this.total  = data.TotalCount
                this.show_list = data.Instances.Instance
            })
        }

    },
    mounted: function() {
        this.regionList()
        setTimeout(() =>{
            this.refresh();
        },1000); 
    }
}
</script>
<style>
    pre{
        white-space: pre-wrap!important;
        word-wrap: break-word!important;
        *white-space:normal!important;
    }
</style>